package com.thlws.study.redismq.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * https://www.cnblogs.com/jajian/p/10051901.html
 * https://github.com/alibaba/fastjson/wiki/enable_autotype
 * @author HanleyTang 2019-07-31
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }


    @Bean("myRedisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        //JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
        //GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

//        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class); //定义类型专用
//        ParserConfig parserConfig = fastJsonRedisSerializer.getFastJsonConfig().getParserConfig();
//        parserConfig.setAutoTypeSupport(false);
//        parserConfig.addAccept("com.baidu");

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();

        // 全局开启AutoType，GenericFastJsonRedisSerializer 已开启
         //ParserConfig.getGlobalInstance().setAutoTypeSupport(false);
        // 小范围指定白名单,不开启反序列会失败,测试无效，待验证
        //ParserConfig.getGlobalInstance().addAccept("com.thlws.study.redismq.model");

         //设置默认后,key也是json格式，So 分别设置key，value的序列化方式
        //redisTemplate.setDefaultSerializer(genericFastJsonRedisSerializer);
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}
